package com.smart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.pojo.Role;
import com.smart.mapper.RoleMapper;
import com.smart.pojo.User;
import com.smart.req.RoleReq;
import com.smart.resp.RoleResp;
import com.smart.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lyj
 * @since 2023-04-21
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    IUserService userService;

    @Override
    public Page<RoleResp> queryPageByCondition(RoleReq roleReq, Page<RoleResp> rolePage) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.apply("r.del_flag=0")
                .eq(!ObjectUtils.isEmpty(roleReq.getDepartmentId()), "r.department_id", roleReq.getDepartmentId())
                .and(!ObjectUtils.isEmpty(roleReq.getKeyWord()),
                        qw -> qw.like("r.name", roleReq.getKeyWord())
                                .or()
                                .like("r.remark", roleReq.getKeyWord()));

        return baseMapper.selectRoleRespPageByCondition(rolePage, wrapper);
    }

    @Override
    @Transactional
    public boolean deleteById(Long id) {
        //将该角色下的用户解除角色关系
        List<User> users = userService.queryByRoleIdAndKeyword(id, null);
        for (User user : users) {
            user.setRoleId(null);
        }
        boolean rs = userService.updateBatchById(users);

        //删除角色
        return this.removeById(id);
    }
}
